/**
 * @author wangze
 * @date 2017-12-19 13:42.
 **/

(function () {
    var _bt = window.BT,
        _util = _bt.util,
        _dialog = _util.dialog,
        _config = _util.config,
        _uUrl = _config.url.user,
        _enum = _config.enumValues,
        _uStatusEnum = _enum.userStatus,
        _debug = _util.debug;

    var gridOpt = {
        url: _uUrl.list,
        formatters: {
            'statusFormat': function (column, row) {
                var r = _enum.getSelected(_uStatusEnum, row.status);
                if (!(r && r.name)) {
                    return '';
                }
                switch (row.status) {
                    case _uStatusEnum.forbidden.value:
                        return '<button class="btn btn-xs btn-danger command-status-change"  data-row-id="' + row.id + '" data-row-status="' + row.status + '">' + r.name + '</button> ';
                    case _uStatusEnum.start.value:
                        return '<button class="btn btn-xs btn-success command-status-change"  data-row-id="' + row.id + '" data-row-status="' + row.status + '">' + r.name + '</button> ';
                    default:
                        return '';
                }
            },
            'commands': function (column, row) {
                return '<button class="btn btn-xs btn-purple command-edit" data-row-id="' + row.id + '">用户管理</button>';
            },
            'areaFormat': function (column, row) {
                var str = row.dataRangeStr;
                if (str && str.length > 32) {
                    str = str.substr(0, 32) + '...';
                }
                return '<p title="{1}">{0}</p>'.format(str, row.dataRangeStr);
            }
        }
    };

    var page = {
        grid: null,
        init: function () {
            var formSearch = '#form-search';
            page.grid = new _bt.BGrid(gridOpt);
            page.common.platFormInit($('[name=platformID]', formSearch), '-全部-');
            page.common.ajaxSelectInit($('[name=rolesID]', formSearch), _config.url.platform.column, '-全部-');
            page.common.selectInit($('[name=status]', formSearch), _enum.getArray(_enum.userStatus), '-全部-');
            page.bind();
        }

    };

    page.common = {
        /**
         * select 公共方法
         * @param ele
         * @param data
         * @param _emptyText
         */
        selectInit: function (ele, data, _emptyText) {
            var html = ['<option value="">{0}</option>'.format(_emptyText)];
            $.each(data, function (i, item) {
                html.push('<option value="' + item.value + '">' + item.name + '</option>');
            });
            ele.html(html.join(''));
        },
        ajaxSelectInit: function (ele, url, emptyText) {
            var renderHtml = function (data) {
                var html = ['<option value="">' + emptyText + '</option>'];
                $.merge(html, $.map(data, function (n, i) {
                    return '<option value="{0}">{1}</option>'.format(n.id, n.name);
                }));
                return html.join('');
            };
            var successEvent = function (data) {
                if (data && data.flag) {
                    data = data.data;
                    ele.html(renderHtml(data));
                } else {
                    _dialog.warn('获取栏目样式失败');
                }
            };
            _util.ajax({
                url: url,
                type: 'get',
                async: false
            }, successEvent);
        },
        platFormInit: function (ele, emptyText) {
            page.common.ajaxSelectInit(ele, _uUrl.platform, emptyText);
        }
    };


    page.tree = {
        ele: null,
        id: '#treeDemo',
        radioPrefix: 'isReadOnly',
        addTree: function (zNodes) {
            zNodes = page.tree.formatTreeData(zNodes);
            var IDMark_A = "_a";
            var addDiyDom = function addDiyDom(treeId, treeNode) {
                if (!treeNode.isSys) {return;}
                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                var aObj = $("#" + treeNode.tId + IDMark_A);
                //var editStr = "<input type='radio' name='isReadOnly-" + treeNode.id + "' checked='checked'  value='true'>只读 <input type='radio' name='isReadOnly-" + treeNode.id + "' value='false'>可操作";
                var editStr = "<input type='radio' name='isReadOnly-" + treeNode.id + "'  value='true'>只读 <input type='radio' name='isReadOnly-" + treeNode.id + "' value='false'>可操作";
                aObj.after(editStr);
                aObj.siblings('[name^=isReadOnly]:radio').on('click', function () {
                    var node = tree.getNodeByParam("id", $(this).attr('name').split('-')[1], null);
                    treeObj.checkNode(node, true, false);
                });
            };
            var setting = {
                check: {
                    enable: true,
                    chkboxType: {"Y": "ps", "N": "ps"}
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: 'id',
                        pIdKey: 'pId',
                        rootPId: 0
                    }
                },
                callback: {
                    onCheck: function (event, treeId, treeNode) {
                        var $radioReadOnly = $('[name=isReadOnly-{0}]'.format(treeNode.id));
                        if (treeNode.isSys) {
                            if (treeNode.checked === true) {
                                $radioReadOnly.eq(0).prop('checked', true);
                            } else {
                                $radioReadOnly.prop('checked', false);
                            }

                        }
                        $('[name=tree]').blur();
                    }
                },
                view: {
                    addDiyDom: addDiyDom
                }
            };
            var $t = $(page.tree.id);
            var tree = $.fn.zTree.init($t, setting, zNodes);
            $t.closest('.form-group').show();
            page.tree.ele = tree;
            return tree;
        },
        getSelected: function () {
            var tree = page.tree.ele;
            if (!tree) {
                _dialog.warn('获取栏目权限失败，请重新打开');
                return false;
            }
            var data = tree.getCheckedNodes(true);
            return $.map(data || [], function (item, i) {
                var isReadOnly;
                if (item.isSys) {
                    isReadOnly = $('[name=' + page.tree.radioPrefix + '-' + item.id + ']:checked').val();
                    return {'menuId': item.id, isReadOnly: isReadOnly};
                } else {
                    return {'menuId': item.id};
                }

            });
        },
        //选中节点
        selectNode: function (data) {
            var tree = page.tree.ele;
            var selectTreeNodeData = $.grep(data || [], function (n, i) {
                return n.isChecked === true;
            });
            $.each(selectTreeNodeData, function (i, item) {
                var node = tree.getNodeByParam("id", item.id, null);
                tree.checkNode(node, true, false);
            });
            page.tree.selectRadio(selectTreeNodeData);
        },
        /**
         * 选中radio
         */
        selectRadio: function (data) {
            $.each(data || [], function (i, item) {
                if (item.issys === true) {
                    if (item.isReadOnly === true || item.isReadOnly === false) {
                        $('[name=' + page.tree.radioPrefix + '-' + item.id + '][value=' + item.isReadOnly + ']').prop('checked', true);
                    }
                }
            });

        },
        /**
         *获取格式化的树形菜单
         * @param data
         */
        formatTreeData: function (data) {
            return $.map(data || [], function (item, i) {
                var data = {
                    id: item.id,
                    pId: item.parentid,
                    name: item.name,
                    checked: item.isChecked || false,
                    open: true,
                    isSys: item.issys
                };
                //如果是父级菜单 则不需要关注 是否可操作，只读属性
                if (data.pId === 0) {
                    delete  data.isSys;
                }
                return data;

            });
        }

    };

    /**
     *编辑页面
     */
    page.edit = {
        form: '#form-edit',
        dialog: null,
        addValidateRule: function () {
            page.edit.deleteValidateRule();
            $.validator.addMethod('userName', function (value, element) {
                return this.optional(element) || /^[A-Za-z][A-Za-z1-9_-]+$/.test(value);
            }, "字母开头 + 数字/字母/下划线");

            $.validator.addMethod('pwd', function (value, element) {
                return this.optional(element) || /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value);
            }, "密码必须6-26位，且不能为纯数字");

            $.validator.addMethod('tel', function (value, element) {
                return this.optional(element) || (/^1(3|4|5|7|8)\d{9}$/.test(value) || /^0\d{2,3}-[1-9]\d{6,7}$/.test(value));
            }, "请输入电话或手机号");

            $.validator.addMethod('treeRequired', function (value, element) {
                if (!page.tree.ele) {return false;}
                var selectedNodes = page.tree.ele.getCheckedNodes(true);
                return selectedNodes && selectedNodes.length > 0;
            }, "必选");
            $.validator.addMethod('userNameDistinct', function (value, element) {
                var isSuccess = false;
                var successEvent = function (data) {
                    if (data && data.flag) {
                        isSuccess = true;
                    } else {
                        // _dialog.info('验证用户名重复失败');
                    }
                };
                //编辑的时候，如果用户名不变，则不校验用户名重复
                var originName = $(element).attr('data-origin-name');
                if (originName && value === originName) {
                    return this.optional(element) || true;
                }

                _util.ajax({
                    url: _uUrl.nameDistinct,
                    type: 'get',
                    async: false,
                    data: {userName: value}
                }, successEvent);
                return this.optional(element) || isSuccess;
            }, '用户名重复');

        },
        deleteValidateRule: function () {
            delete  $.validator.methods.treeRequired;
            delete  $.validator.messages.treeRequired;
        },
        addValidate: function (f) {
            page.edit.addValidateRule();
            var validateOpt = {
                rules: {
                    name: {required: true, userNameDistinct: true, userName: true},
                    nickname: {required: true},
                    pwd: {required: true, pwd: true},
                    platformid: {required: true},
                    tel: {required: true, tel: true},
                    status: {required: true},
                    dataRangeStr: {required: true},
                    tree: {
                        treeRequired: true
                    }
                },
                messages: {
                    name: {required: '必填'},
                    nickname: {required: '必填'},
                    pwd: {required: '必填'},
                    platformid: {required: '必填'},
                    tel: {required: '必填'},
                    status: {required: '必填'},
                    dataRangeStr: {required: '必选1个'}
                },
                ignore: '.hidden',
                submitHandler: function (form) {
                    var successEvent = function (data) {
                        if (data && data.flag) {
                            _dialog.info('保存成功');
                            page.edit.hide();
                            page.grid.reload();
                        } else {
                            _dialog.warn('保存失败');
                        }
                    };
                    //删除一些属性
                    var delProperty = function (data, propertyName) {
                        var tmp = [];
                        $.each(data, function (k, v) {
                            if (k.indexOf(propertyName) != -1) {
                                tmp.push(k);
                            }
                        });
                        $.each(tmp, function (i, item) {
                            delete  data[item];
                        });
                    };
                    var getSubmitData = function () {
                        var data = $(form).serializeObject();
                        var treeNodes = page.tree.getSelected();
                        var rangeName = 'dataRangeStr';
                        delProperty(data, 'isReadOnly');
                        delProperty(data, 'tree');
                        if (data[rangeName]) {
                            if ($.isArray(data[rangeName])) {
                                data[rangeName] = data[rangeName].join(',');
                            }
                        } else {
                            data[rangeName] = '';
                            //throw  new Error('当前平台没有数据范围，不能保存，请重新选择')
                        }

                        data.menuparam = treeNodes;
                        return data;
                    };

                    try {
                        _util.jsonAjax({
                            url: _uUrl.save,
                            data: getSubmitData()
                        }, successEvent);
                    } catch (err) {
                        _dialog.warn(err.message);
                    }

                }
            };
            return f.validate($.extend({}, _util.validate.default, validateOpt));
        },
        /**
         * 添加栏目样式
         */
        addPlatform: function (ele) {
            var $areaContainer;
            var parentCheckBoxName = '#rangeParent';
            var subCheckBoxClassName = '.sub-range';
            page.common.platFormInit(ele, '-请选择-');
            $areaContainer = $('#area-contain');
            //根据平台 切换菜单事件
            ele.on('change', function (event, async) {
                    var $self = $(this);
                    if (!$self.val()) {
                        $(page.tree.id).closest('.form-group').hide();
                        $areaContainer.closest('.form-group').hide();
                        return;
                    }
                    var menuSuccessEvent = function (data) {
                        if (data && data.flag) {
                            data = data.data;
                            page.tree.addTree(data);
                        } else {
                            _dialog.warn('获取菜单失败');
                        }
                    };
                    //分段显示
                    var sectionArray = function (l, array) {
                        var arrayLength, b, c, i, d = [];
                        arrayLength = array.length;
                        b = Math.floor(arrayLength / l);
                        for (i = 1; i <= b; i++) {
                            d.push('<div style="margin-left:35px;">' + array.slice((i - 1) * l, i * l).join('') + '</div>');
                        }
                        c = arrayLength % l;
                        if (c > 0) {
                            d.push('<div style="margin-left:35px;">' + array.slice(l * b).join('') + '</div>');
                        }
                        return d;
                    };
                    var renderDataHtml = function (data) {
                        var html = ['<div ><input type="checkbox"  id="{1}"><span>{0}</span></div>'.format(data.parentName, parentCheckBoxName.substring(1))];
                        var tmp = [];
                        $.each(data.paEntities, function (i, item) {
                            tmp.push('<input type="checkbox" name="dataRangeStr" value="{0}" class="{2}"><span>{1}</span>'.format(item.id, item.name, subCheckBoxClassName.substring(1)))
                        });
                        return html.concat(sectionArray(5, tmp)).join('');
                    };

                    var dataAreaSuccessEvent = function (data) {
                        var $parentCheckBox, $subCheckBox;
                        if (data && data.flag) {
                            data = data.data;
                            $areaContainer.closest('.form-group').show();
                            $areaContainer.html(renderDataHtml(data));
                            $parentCheckBox = $(parentCheckBoxName, $areaContainer);
                            $subCheckBox = $(subCheckBoxClassName, $areaContainer);

                            //数据范围 父级菜单事件绑定
                            $(parentCheckBoxName, $areaContainer).on('click', function () {
                                $(subCheckBoxClassName, $areaContainer).prop('checked', $(this).prop('checked'));
                            });
                            //数据范围 子级菜单事件绑定
                            $subCheckBox.on('click', function () {
                                var hasFalse = false;
                                $subCheckBox.each(function (i, item) {
                                    if (!$(this).prop('checked')) {
                                        $parentCheckBox.prop('checked', false);
                                        hasFalse = true;
                                        return false;
                                    }
                                });
                                if (!hasFalse && $subCheckBox.length > 0) {
                                    $parentCheckBox.prop('checked', true);
                                }
                            });
                            if (!(async === false) && $subCheckBox.length > 0) {
                                $parentCheckBox.click();
                            }
                        } else {
                            _dialog.warn('加载数据区域失败');
                        }
                    };
                    /**
                     * 加载菜单
                     */
                    _util.ajax({
                        url: _uUrl.menu,
                        type: 'get',
                        async: !(async === false),
                        data: {platformId: $self.val()}
                    }, menuSuccessEvent);


                    if ($self.val()) {
                        /**
                         * 加载数据范围
                         */
                        _util.ajax({
                            url: _uUrl.dataArea,
                            type: 'get',
                            async: !(async === false),
                            data: {platformId: $self.val()}
                        }, dataAreaSuccessEvent);
                    }

                });

        },
        /**
         * 编辑页面获取数据
         * @param id
         */
        loadData: function (id) {
            var $form = $('#form-edit');
            var $platform = $('[name=platformid]', $form);
            //绑定菜单事件
            var bindFormData = function (data) {
                var selectDataRange;
                $platform.val(data.platformid).trigger('change', false);
                //设置数据范围
                selectDataRange = $.map($.grep(data.dataRangeModel.paEntities || [], function (n, i) {
                    return n.isChecked === true;
                }), function (n, i) {
                    return n.id
                });
                data.dataRangeStr = selectDataRange;
                page.tree.selectNode(data.webMenuModels);
                $form.bindForm(data);
                $($('.sub-range').get(0)).click().click();
                //修改的时候绑定 原始用户姓名
                $('[name=name]', $form).attr('data-origin-name', data.name);
            };

            var editSuccessEvent = function (data) {
                if (!(data && data.flag)) {
                    //_debug.log(data);
                    return;
                }
                data = data.data;
                if (!data) {
                    _debug.log('没有获取到数据');
                    return;
                }
                bindFormData(data);
            };
            /**
             * 添加一些初始的事件
             */
            page.edit.addPlatform($platform);
            page.common.selectInit($('[name=status]', $form), _enum.getArray(_enum.userStatus), '-请选择-');
            page.edit.addValidate($form);
            /**
             * 修改
             */
            if (id) {
                _util.ajax({
                    url: _uUrl.data,
                    type: 'get',
                    data: {id: id}
                }, editSuccessEvent);
            }

        },
        show: function (title, id) {
            var m = _dialog.edit({
                message: $('#edit-template').html(),
                title: title
            }, {
                init: function () {
                    page.edit.loadData(id);
                },
                success: function () {
                    $('#form-edit').submit();
                    return false;
                }
            });

            page.edit.dialog = m;
            return m;
        },
        hide: function () {
            page.edit.dialog && page.edit.dialog.modal('hide');
        }
    };
    /**
     * 页面事件绑定
     */
    page.bind = function () {
        var showDialog = page.edit.show;
        var searchEvent = function () {
            page.grid.reload();
        };
        var addEvent = function () {
            showDialog('新增用户');
        };
        var delEvent = function () {
            //选择数据
            var ids = page.grid.getSelections();
            if (ids.length === 0) {
                _dialog.warn('请选择一条数据');
                return;
            }
            _dialog.confirm('确定删除吗?', function () {
                _util.ajax({
                    type: 'get',
                    url: _uUrl.del,
                    data: {ids: ids.join(',')}
                }, function (data) {
                    if (data && data.flag) {
                        _dialog.info('删除成功');
                        page.grid.reload();
                    } else {
                        _dialog.warn('删除失败');
                    }
                });
            });
        };
        $('#btn-search').on('click', searchEvent);
        $('#btn-add').on('click', addEvent);
        $('#btn-del').on('click', delEvent);

        /**
         * 绑定grid上的编辑事件
         */
        page.grid.on('loaded', function () {
            var changeEvent = function () {
                var $self = $(this),
                    id = $self.attr('data-row-id'),
                    status = $self.attr('data-row-status');
                var getStatus = function () {
                    switch (parseInt(status, 10)) {
                        case _uStatusEnum.forbidden.value:
                            return _uStatusEnum.start.value;
                        case _uStatusEnum.start.value:
                            return _uStatusEnum.forbidden.value;
                        default:
                            _dialog.alert('当前用户类型不存在，请刷新页面');
                            break;
                    }
                };
                var successEvent = function (data) {
                    if (data && data.flag) {
                        _dialog.info('操作成功');
                        page.grid.load();
                    } else {
                        _dialog.info('操作失败');
                    }
                };
                _util.ajax({
                    type: 'get',
                    url: _uUrl.changeStatus,
                    data: {
                        id: id,
                        status: getStatus()
                    }
                }, successEvent);
            };

            $('.command-edit').on('click', function () {
                var id = $(this).attr('data-row-id');
                page.edit.show('用户管理', id);
                return false;
            });
            /**
             * 变更状态
             */
            $('.command-status-change').on('click', changeEvent);
        });
    };

    $(function () {
        page.init();
    });

})();